package com.cdzy.service.impl;

import com.cdzy.common.ApiException;
import com.cdzy.common.ApiExceptionCodeMsg;
import com.cdzy.mapper.BookMapper;
import com.cdzy.pojo.Book;
import com.cdzy.pojo.BookType;
import com.cdzy.pojo.EntityVO;
import com.cdzy.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    BookMapper bookMapper;

    @Override
    public List<BookType> getBookTypeList() {
        return bookMapper.selectBookTypeList();
    }

    @Override
    public List<Book> getBookListByType(int id) {
        Book book = new Book();
        // 当id不为0时，设置typeId
        if (id != 0) {
            book.setTypeId(id);
        }
        return bookMapper.getBookListByType(book);
    }

    @Override
    public EntityVO getBookList() {
        List<Book> list =bookMapper.getBookList();
        int total = bookMapper.selectBookListCount();
        if (list.size() < 1){
            throw new ApiException(ApiExceptionCodeMsg.NO_DATA_FOUND);
        }
        EntityVO entityVO = new EntityVO();
        entityVO.setList(list);
        entityVO.setTotal(total);
        return entityVO;
    }
    /**
     * 通过ID查询单条数据
     *
     * @param bookId 主键
     * @return 实例对象
     */
    public Book queryById(Integer bookId) {
        return this.bookMapper.queryById(bookId);
    }


    /**
     * 新增数据
     *
     * @param books 实例对象
     * @return 实例对象
     */
    public Book insert(Book books) {
        this.bookMapper.insert(books);
        return books;
    }

    /**
     * 修改数据
     *
     * @param books 实例对象
     * @return 实例对象
     */
    public Book update(Book books) {
        this.bookMapper.update(books);
        return this.queryById(books.getBookId());
    }

    /**
     * 通过主键删除数据
     *
     * @param bookId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer bookId) {
        return this.bookMapper.deleteById(bookId);
    }
}